from .base_strategy import BaseStrategy
import backtrader as bt
import indicator.MyTTIndicator as Mytt
import indicator.myzhibiao as mmm


###
# MACD 死叉后，10根k线内，突破唐奇安通道上轨 则做多
# 金叉做多，死叉开空
# 固定2%止损，固定10根k线后止盈
# #
class MyStrategy(BaseStrategy):
    params = (
        ('macd_short', 12),
        ('macd_long', 26),
        ('macd_signal', 9),
        ('donchian_period', 25),
        ('atr_period', 14),
        ('stop_loss_multiplier', 2),
        ('take_profit_multiplier', 2),
        ('entry_window', 10),
    )
 
    def __init__(self):
        super().__init__()

        self.init_indicators()

        self.order = None
        self.entry_bar = None
    
    def init_indicators(self):
        """在此定义指标 (EMA/MACD/RSI等)"""
        # RD(DIF),RD(DEA),RD(MACD)
        # 计算macd
        bt.ind.EMA()
        bt.indicators.EMA()
        # self.macd_dif,self.macd_dea,self.macd_macd = Mytt.MyTT_MACD(self.data, short=self.p.macd_short, long=self.p.macd_long, signal=self.p.macd_signal)
        # self.macd = Mytt.MyTT_MACD(self.data, short=self.p.macd_short, long=self.p.macd_long, signal=self.p.macd_signal)
        # print(self.macd[-1],'--msss')
        self.macd =  mmm.MACD(self.data, short=self.p.macd_short, long=self.p.macd_long, signal=self.p.macd_signal)
        # self.macd_cross = bt.indicators.CrossOver(self.macd, self.long_ma)
        # UP,MID,DOWN
        # 计算唐奇安通道
        self.donchian = mmm.DonchianChannel(self.data, period=self.p.donchian_period,plot=False)
        # 将通道绘制在主图上
        bt.indicators.Highest(self.donchian.upper, period=self.p.donchian_period, 
                            plotmaster=self.data, subplot=False, plotname='up')
                # 中轨
        bt.indicators.Lowest(self.donchian.middle, period=self.p.donchian_period, 
                           plotmaster=self.data, subplot=False, plotname='middle')
        bt.indicators.Lowest(self.donchian.lower, period=self.p.donchian_period, 
                           plotmaster=self.data, subplot=False, plotname='low')


        self.atr = mmm.ATR(self.data, period=self.p.atr_period,plot=False)


    def notify_order(self, order):
        super().notify_order(order)

    def notify_trade(self, trade):
        if not trade.isclosed:
            return
            
        print(f'交易盈亏, 毛利: {trade.pnl:.2f}, 净利: {trade.pnlcomm:.2f}')

    def next(self):
        super().next()

        # print(self.macd.dif[0])
        # exit()
        # 标记金叉死叉出现的k线
        # if not self.position and self.macd_dif[0] < self.macd_dea[0] and self.macd_dif[-1] >= self.macd_dea[-1]:
            # self.entry_bar = len(self)
        if not self.position and self.macd.macd[0] < self.macd.signal[0] and self.macd.macd[-1] >= self.macd.signal[-1]:
            self.entry_bar = len(self)
 
        # Check for entry condition
        if not self.position and self.entry_bar is not None and (len(self) - self.entry_bar) <= self.p.entry_window:
            # 收盘价突破通道 
            if self.data.close[0] > self.donchian.upper[0]:
                self.order = self.buy()
                entry_price = self.data.close[0]
                self.stop_loss_price = entry_price - 2 * self.atr.atr[0]
                self.take_profit_price = entry_price + 2 * self.atr.atr[0]
 
        # Set stop loss and take profit
        if self.position:
            if self.data.close[0] <= self.stop_loss_price:
                self.close()
            elif self.data.close[0] >= self.take_profit_price:
                self.close()